package service

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"net/http"

	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"

	"go-admin/app/admin/models"
	"go-admin/app/admin/service/dto"
	"go-admin/common/actions"
	cDto "go-admin/common/dto"
)

type SysDevice struct {
	service.Service
}

// GetPage 获取SysDevice列表
func (e *SysDevice) GetPage(c *dto.SysDeviceGetPageReq, p *actions.DataPermission, list *[]models.SysDevice, count *int64) error {
	var err error
	var data models.SysDevice
	var where = ""
	switch c.IsBand {
	case 1:
		where += " dept_id = 0"
	case 2:
		where += " dept_id > 0"
	}

	err = e.Orm.Model(&data).Preload("Dept").
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).Where(where).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	var deviceIds []string
	for _, v := range *list {
		deviceIds = append(deviceIds, v.DeviceId)
	}

	deviceMap := make(map[string]models.SysDevice, 0)
	for _, v := range *list {
		deviceMap[v.DeviceId] = v
	}

	// 查询通道
	var channels []*models.SysChannel
	e.Orm.Model(&models.SysChannel{}).
		Where("device_id IN ?", deviceIds).
		Find(&channels)

	channelMap := make(map[string][]*models.SysDevice, 0)
	for _, c := range channels {
		v := &models.SysDevice{}
		v.CID = c.Id
		v.IsChannel = true
		v.DeviceId = c.ChannelId
		v.Name = c.Name
		v.ParentId = c.DeviceId
		v.Status = c.Status
		v.ActiveAt = c.ActiveAt
		v.CreatedAt = c.CreatedAt
		v.UpdatedAt = c.UpdatedAt
		v.DeptId = deviceMap[c.DeviceId].DeptId
		v.Dept = deviceMap[c.DeviceId].Dept

		channelMap[c.DeviceId] = append(channelMap[c.DeviceId], v)
	}

	// 绑定通道
	for i := 0; i < len(*list); i++ {
		(*list)[i].Children = channelMap[(*list)[i].DeviceId]
	}
	if err != nil {
		e.Log.Errorf("SysDeviceService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取SysDevice对象
func (e *SysDevice) Get(d *dto.SysDeviceGetReq, p *actions.DataPermission, model *models.SysDevice) error {
	var data models.SysDevice

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetSysDevice error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// GetChannel 获取SysDevice通道对象
func (e *SysDevice) GetChannel(d *dto.SysDeviceGetReq, model *models.SysChannel) error {
	var data models.SysChannel

	err := e.Orm.Model(&data).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetSysDevice error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建SysDevice对象
func (e *SysDevice) Insert(c *dto.SysDeviceInsertReq) error {
	var err error
	var data models.SysDevice
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("SysDeviceService Insert error:%s \r\n", err)
		return err
	}
	return nil
}

// Update 修改SysDevice对象
func (e *SysDevice) Update(c *dto.SysDeviceUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.SysDevice{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("SysDeviceService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

// UpdateChannel 修改SysDevice通道对象
func (e *SysDevice) UpdateChannel(c *dto.SysDeviceUpdateReq) error {
	var err error
	var data = models.SysChannel{}
	e.Orm.Model(&models.SysChannel{}).First(&data, c.GetId())
	// 只更新通道名称
	data.Name = c.Name
	data.UpdateBy = c.UpdateBy

	db := e.Orm.Omit("ActiveAt").Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("SysDeviceService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

// Remove 删除SysDevice
func (e *SysDevice) Remove(d *dto.SysDeviceDeleteReq, p *actions.DataPermission) error {
	var data models.SysDevice
	// 查找设备
	e.Orm.Model(&models.SysDevice{}).First(&data, d.GetId())
	deviceId := data.DeviceId
	// 先删除设备通道
	e.Orm.Model(&models.SysChannel{}).
		Where("device_id = ?", deviceId).
		Delete(&models.SysChannel{})

	// 删除设备
	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveSysDevice error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

type SipServerResponse struct {
	Code string `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		DeviceID  string `json:"deviceid"`
		ChannelID string `json:"channelid"`
		StreamID  string `json:"streamid"`
		WSFLV     string `json:"wsflv"`
		Audioport int    `json:"audioport"`
	} `json:"data"`
}

func (e *SysDevice) GetRealTimePlayUrl(c *dto.SysChannelPlayReq) error {
	// 创建 http.Client 实例
	client := &http.Client{}
	req, err := http.NewRequest("POST", c.SipHost+"/channels/"+c.Id+"/streams", nil)
	if err != nil {
		e.Log.Errorf("Service GetRealTimePlayUrl error:%s \r\n", err)
		return err
	}
	req.Header.Add("Authorization", c.Key)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	resp, err := client.Do(req)
	if err != nil {
		e.Log.Errorf("Service GetRealTimePlayUrl error:%s \r\n", err)
		return err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		e.Log.Errorf("Service GetRealTimePlayUrl error:%s \r\n", err)
		return err
	}

	// 解析json
	var data SipServerResponse
	err = json.Unmarshal(body, &data)
	if err != nil {
		// e.Log.Errorf("Service GetRealTimePlayUrl error:%s \r\n", err)
		err = errors.New("通道离线或者不存在")
		return err
	}
	if data.Code != "0" {
		e.Log.Errorf("Service GetRealTimePlayUrl error:%s \r\n", data.Msg)
		return errors.New(data.Msg)
	} else {
		c.Url = data.Data.WSFLV
	}

	return nil
}

func (e *SysDevice) Control(c *dto.SysDeviceControlReq) error {
	// 创建 http.Client 实例
	client := &http.Client{}
	apiAddr := c.SipHost + "/control/" + c.Id
	// 判断是否是语音对讲指令
	if c.Cmd == "audio" {
		apiAddr = c.SipHost + "/channels/" + c.Id + "/broadcast"
	}
	req, err := http.NewRequest("POST", apiAddr, nil)
	if err != nil {
		e.Log.Errorf("Service Control error:%s \r\n", err)
		return err
	}
	req.Header.Add("Authorization", c.Key)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	// 构建表单数据
	formData := "cmd=" + c.Cmd
	// 构建请求体
	reqBody := bytes.NewBufferString(formData)
	req.Body = io.NopCloser(reqBody)

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		e.Log.Errorf("Service Control error:%s \r\n", err)
		return err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		e.Log.Errorf("Service Control error:%s \r\n", err)
		return err
	}

	// 解析json
	var data SipServerResponse
	err = json.Unmarshal(body, &data)
	if err != nil {
		e.Log.Errorf("Service Control error:%s \r\n", err)
		err = errors.New("通道离线或者不存在")
		return err
	}
	if data.Code != "0" {
		e.Log.Errorf("Service Control Device error:%s \r\n", data.Msg)
		return errors.New(data.Msg)
	}
	// 语音对讲指令需要返回音频推流端口
	if c.Cmd == "audio" {
		c.Audioport = data.Data.Audioport
	}

	return nil
}
